<template>
  <div class="log-management">
    <div class="page-header">
      <h2>{{ $t('common.logManagement') }}</h2>
      <p>{{ $t('common.logManagementDescription') }}</p>
    </div>
    
    <div class="search-container">
      <div class="search-item">
        <label>{{ $t('log.operateUser') }}:</label>
        <InputText v-model="searchParams.operateUser" placeholder="{{ $t('common.pleaseInput') }}" />
      </div>
      <div class="search-item">
        <label>{{ $t('log.operateModule') }}:</label>
        <InputText v-model="searchParams.operateModule" placeholder="{{ $t('common.pleaseInput') }}" />
      </div>
      <div class="search-item">
        <label>{{ $t('log.operateType') }}:</label>
        <Dropdown
          v-model="searchParams.operateType"
          :options="operateTypeOptions"
          placeholder="{{ $t('common.pleaseSelect') }}"
          optionValue="value"
          optionLabel="label"
        />
      </div>
      <div class="search-item">
        <label>{{ $t('log.operateStatus') }}:</label>
        <Dropdown
          v-model="searchParams.operateStatus"
          :options="operateStatusOptions"
          placeholder="{{ $t('common.pleaseSelect') }}"
          optionValue="value"
          optionLabel="label"
        />
      </div>
      <div class="search-item">
        <label>{{ $t('common.beginTime') }}:</label>
        <Calendar v-model="searchParams.beginTime" dateFormat="yy-mm-dd" placeholder="{{ $t('common.pleaseSelect') }}" />
      </div>
      <div class="search-item">
        <label>{{ $t('common.endTime') }}:</label>
        <Calendar v-model="searchParams.endTime" dateFormat="yy-mm-dd" placeholder="{{ $t('common.pleaseSelect') }}" />
      </div>
      <div class="search-actions">
        <Button @click="search" icon="pi pi-search">{{ $t('common.search') }}</Button>
        <Button @click="reset" icon="pi pi-refresh">{{ $t('common.reset') }}</Button>
        <Button @click="handleExport" icon="pi pi-download" severity="info">{{ $t('common.export') }}</Button>
      </div>
    </div>
    
    <div class="table-container">
      <DataTable
        :value="logStore.getOperationLogList"
        :loading="logStore.getLoading"
        :paginator="true"
        :rows="searchParams.pageSize"
        :first="(searchParams.page - 1) * searchParams.pageSize"
        :totalRecords="logStore.getOperationLogTotal"
        @page="onPageChange"
        @sort="onSortChange"
        rowHover
      >
        <Column field="id" header="{{ $t('log.logId') }}" sortable></Column>
        <Column field="operateUser" header="{{ $t('log.operateUser') }}" sortable></Column>
        <Column field="operateTime" header="{{ $t('log.operateTime') }}" sortable></Column>
        <Column field="operateModule" header="{{ $t('log.operateModule') }}" sortable></Column>
        <Column field="operateType" header="{{ $t('log.operateType') }}" sortable>
          <template #body="{ data }">
            {{ getOperateType(data.operateType) }}
          </template>
        </Column>
        <Column field="operateContent" header="{{ $t('log.operateContent') }}">
          <template #body="{ data }">
            <Tooltip target="#log-content-{{ data.id }}" content="{{ data.operateContent }}" position="top" />
            <span :id="`log-content-${data.id}`" class="log-content-tooltip" :title="data.operateContent">{{ data.operateContent }}</span>
          </template>
        </Column>
        <Column field="operateStatus" header="{{ $t('log.operateStatus') }}">
          <template #body="{ data }">
            <Badge :severity="data.operateStatus === 0 ? 'success' : 'danger'">
              {{ data.operateStatus === 0 ? $t('common.success') : $t('common.fail') }}
            </Badge>
          </template>
        </Column>
        <Column field="ip" header="{{ $t('log.ip') }}"></Column>
        <Column field="userAgent" header="{{ $t('log.userAgent') }}">
          <template #body="{ data }">
            <Tooltip target="#log-agent-{{ data.id }}" content="{{ data.userAgent }}" position="top" />
            <span :id="`log-agent-${data.id}`" class="log-content-tooltip" :title="data.userAgent">{{ data.userAgent }}</span>
          </template>
        </Column>
        <Column header="{{ $t('common.operate') }}" style="width: 8rem">
          <template #body="{ data }">
            <Button @click="handleDelete(data.id)" icon="pi pi-trash" size="small" severity="danger"></Button>
          </template>
        </Column>
      </DataTable>
    </div>
    
    <!-- 批量操作 -->
    <div class="batch-actions" v-if="selectedLogs.length > 0">
      <span>{{ $t('common.selected') }} {{ selectedLogs.length }} {{ $t('common.items') }}</span>
      <Button @click="handleBatchDelete" severity="danger">{{ $t('common.batchDelete') }}</Button>
      <Button @click="handleClearAll" severity="warning">{{ $t('log.clearAll') }}</Button>
    </div>
    
    <!-- 日志详情对话框 -->
    <Dialog v-model:visible="detailDialogVisible" :header="$t('log.logDetail')" :modal="true" :style="{ width: '700px' }">
      <div class="detail-container" v-if="currentLog">
        <div class="detail-item">
          <label>{{ $t('log.logId') }}:</label>
          <span>{{ currentLog.id }}</span>
        </div>
        <div class="detail-item">
          <label>{{ $t('log.operateUser') }}:</label>
          <span>{{ currentLog.operateUser }}</span>
        </div>
        <div class="detail-item">
          <label>{{ $t('log.operateTime') }}:</label>
          <span>{{ currentLog.operateTime }}</span>
        </div>
        <div class="detail-item">
          <label>{{ $t('log.operateModule') }}:</label>
          <span>{{ currentLog.operateModule }}</span>
        </div>
        <div class="detail-item">
          <label>{{ $t('log.operateType') }}:</label>
          <span>{{ getOperateType(currentLog.operateType) }}</span>
        </div>
        <div class="detail-item detail-textarea">
          <label>{{ $t('log.operateContent') }}:</label>
          <textarea v-model="currentLog.operateContent" readonly rows="4"></textarea>
        </div>
        <div class="detail-item">
          <label>{{ $t('log.operateStatus') }}:</label>
          <span>
            <Badge :severity="currentLog.operateStatus === 0 ? 'success' : 'danger'">
              {{ currentLog.operateStatus === 0 ? $t('common.success') : $t('common.fail') }}
            </Badge>
          </span>
        </div>
        <div class="detail-item" v-if="currentLog.operateStatus === 1">
          <label>{{ $t('log.errorMsg') }}:</label>
          <textarea v-model="currentLog.errorMsg" readonly rows="3"></textarea>
        </div>
        <div class="detail-item">
          <label>{{ $t('log.ip') }}:</label>
          <span>{{ currentLog.ip }}</span>
        </div>
        <div class="detail-item detail-textarea">
          <label>{{ $t('log.userAgent') }}:</label>
          <textarea v-model="currentLog.userAgent" readonly rows="2"></textarea>
        </div>
      </div>
      <template #footer>
        <Button @click="detailDialogVisible = false">{{ $t('common.close') }}</Button>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { useLogStore } from '../../../store/modules/system/log'
import type { OperationLog } from '../../../types/app.d'
import Button from 'primevue/button'
import InputText from 'primevue/inputtext'
import Dropdown from 'primevue/dropdown'
import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
import Badge from 'primevue/badge'
import Dialog from 'primevue/dialog'
import Calendar from 'primevue/calendar'
import Tooltip from 'primevue/tooltip'

const { t } = useI18n()
const logStore = useLogStore()

// 搜索参数
const searchParams = reactive({
  page: 1,
  pageSize: 10,
  operateUser: '',
  operateModule: '',
  operateType: null as string | null,
  operateStatus: null as number | null,
  beginTime: '',
  endTime: ''
})

// 操作类型选项
const operateTypeOptions = [
  { label: t('log.operateTypeAdd'), value: 'add' },
  { label: t('log.operateTypeUpdate'), value: 'update' },
  { label: t('log.operateTypeDelete'), value: 'delete' },
  { label: t('log.operateTypeQuery'), value: 'query' },
  { label: t('log.operateTypeLogin'), value: 'login' },
  { label: t('log.operateTypeLogout'), value: 'logout' },
  { label: t('log.operateTypeImport'), value: 'import' },
  { label: t('log.operateTypeExport'), value: 'export' }
]

// 操作状态选项
const operateStatusOptions = [
  { label: t('common.success'), value: 0 },
  { label: t('common.fail'), value: 1 }
]

// 选中的日志
const selectedLogs = ref<OperationLog[]>([])

// 详情对话框状态
const detailDialogVisible = ref(false)
const currentLog = ref<OperationLog | null>(null)

// 初始化
const init = () => {
  logStore.getOperationLogListAction(searchParams)
}

// 获取操作类型文本
const getOperateType = (operateType: string) => {
  const type = operateTypeOptions.find(option => option.value === operateType)
  return type ? type.label : operateType
}

// 搜索
const search = () => {
  searchParams.page = 1
  logStore.getOperationLogListAction(searchParams)
}

// 重置
const reset = () => {
  Object.assign(searchParams, {
    page: 1,
    pageSize: 10,
    operateUser: '',
    operateModule: '',
    operateType: null,
    operateStatus: null,
    beginTime: '',
    endTime: ''
  })
  logStore.getOperationLogListAction(searchParams)
}

// 页面变化
const onPageChange = (event: any) => {
  searchParams.page = event.page + 1
  searchParams.pageSize = event.rows
  logStore.getOperationLogListAction(searchParams)
}

// 排序变化
const onSortChange = (event: any) => {
  // 实际项目中可以根据排序字段和方向进行排序
  logStore.getOperationLogListAction(searchParams)
}

// 查看日志详情
const handleViewDetail = async (id: string) => {
  await logStore.getOperationLogInfoAction(id)
  if (logStore.getCurrentLog) {
    currentLog.value = { ...logStore.getCurrentLog }
    detailDialogVisible.value = true
  }
}

// 删除日志
const handleDelete = async (id: string) => {
  if (confirm(t('common.confirmDelete'))) {
    const success = await logStore.deleteOperationLogAction(id)
    if (success) {
      logStore.getOperationLogListAction(searchParams)
    }
  }
}

// 批量删除日志
const handleBatchDelete = async () => {
  if (confirm(t('common.confirmBatchDelete'))) {
    const ids = selectedLogs.value.map(log => log.id)
    const success = await logStore.batchDeleteOperationLogAction(ids)
    if (success) {
      selectedLogs.value = []
      logStore.getOperationLogListAction(searchParams)
    }
  }
}

// 清空所有日志
const handleClearAll = async () => {
  if (confirm(t('log.confirmClearAll'))) {
    const success = await logStore.clearAllOperationLogAction()
    if (success) {
      logStore.getOperationLogListAction(searchParams)
    }
  }
}

// 导出日志
const handleExport = async () => {
  const success = await logStore.exportOperationLogAction(searchParams)
  if (success) {
    alert(t('common.exportSuccess'))
  }
}

// 初始化加载数据
init()
</script>

<style scoped>
.log-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.search-container {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  align-items: flex-end;
}

.search-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.search-item label {
  font-weight: 500;
  color: #333;
}

.search-actions {
  display: flex;
  gap: 8px;
  margin-left: auto;
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.log-content-tooltip {
  display: inline-block;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: help;
}

.batch-actions {
  margin-top: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.detail-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.detail-item label {
  width: 120px;
  font-weight: 500;
  color: #333;
  flex-shrink: 0;
}

.detail-item span {
  flex: 1;
  word-break: break-all;
}

.detail-textarea {
  align-items: flex-start;
}

.detail-textarea textarea {
  width: 100%;
  min-height: 80px;
  padding: 8px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  resize: vertical;
  font-family: inherit;
}

.detail-item .p-badge {
  margin-top: 2px;
}
</style>